package com.example.myapplication.screen

import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.material3.Button
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.sp
import androidx.navigation.NavController
import androidx.navigation.compose.NavHost
import androidx.navigation.compose.composable
import androidx.navigation.compose.rememberNavController
import com.google.gson.GsonBuilder


@Composable
fun MyApp() {
    //导航控制器（页面栈）
    val navController = rememberNavController()

    //导航图（路由映射，把页面和路由路径棒的起来）
    NavHost(
        navController = navController,
        startDestination = "home" // 起始页面
    ) {
        composable("home") {
            HomeScreen(navController)
        }
        composable("details/{message}") { backStackEntry ->
            val message = backStackEntry.arguments?.getString("message")
            DetailsScreen(navController, message)
        }
    }
}

data class User(val name: String, val age: Int)

@Composable
fun HomeScreen(navController: NavController) {
    //创建Gson解析器
    val gson = GsonBuilder().create()
    val user = User("张三",20)
    val json = gson.toJson(user)

    Column(
        Modifier
            .fillMaxSize()
            .background(Color.Red),
        horizontalAlignment = Alignment.CenterHorizontally,
        verticalArrangement = Arrangement.Center
    ) {
        Text(
            text = "首页",
            fontSize = 25.sp
        )
        Button(
            onClick = {
                val name = "张三丰"
                navController.navigate("details/$json")
            }
        ) {
            Text(text = "Go to Details")
        }
    }
}

@Composable
fun DetailsScreen(navController: NavController, message: String?) {
    //使用Gson解析json字符串，转换为User对象
    val gson = GsonBuilder().create()
    val user = gson.fromJson<User>(message, User::class.java)

    Column(
        Modifier
            .fillMaxSize()
            .background(Color.Cyan),
        horizontalAlignment = Alignment.CenterHorizontally,
        verticalArrangement = Arrangement.Center
    ) {
        Text(
            text = "详情页${user.name},${user.age}",
            fontSize = 25.sp,
            textAlign = TextAlign.Center
        )
        Button(
            onClick = { navController.navigate("home") }
        ) {
            Text(text = "Back to Home")
        }
    }
}